/**
 * Created by admin on 2017/11/13.
 */
/**
 * Created by admin on 2017/10/26.
 */
$(document).ready(function() {
    var VAL = {
        NORMAL : "0000000",
        EVT_USER     : $("#userId").text(),
        T_MIPWOBOM   : "MIPWOBOM",
        T_MTPMTRLAPY : "MTPMTRLAPY",
        T_FBPBISMTR  : "FBPBISMTR",
        T_FBPBISDAT : "FBPBISDAT",
        DISABLED_ATTR : {
            'disabled' : true
        },
        ENABLED_ATTR : {
            'disabled' : false
        }
    };
    var domObj = {
        buttons : {
            $query_btn    	: $("#query_btn"),
            $save_btn    	: $("#save_btn"),
        },
        $applyType      : $("#applyType"),
        $toolNameId     : $("#toolNameId"),
        grids : {
            $applyListDiv 	: $("#applyListDiv"),
            $applyListGrd 	: $("#applyListGrd"),
            $applyListPg 	: $("#applyListPg"),

            $lendListDiv 	: $("#lendListDiv"),
            $lendListGrd 	: $("#lendListGrd"),
            $lendListPg 	: $("#lendListPg"),

        },
        dialogs : {

        }
    };
    var rowId,cellName;
    var data=[{
        data_ext :'L',
        data_desc:'L:借用',
    },{
        data_ext :'U',
        data_desc:'U:领用',
    }];
    var iniGridInfo = function(){
        var toolListCM = [
            {name: 'evt_seq_id',       index: 'evt_seq_id',            label: MTRL_PROD_ID_FK,  hidden:true,   width: 100},
            {name: 'apply_usr',        index: 'apply_usr',             label: APPLY_USR,           width: 150},
            {name: 'apply_timestamp',  index: 'apply_timestamp',       label: APPLY_TIMESTAMP,     width: 150},
            {name: 'mtrl_name',        index: 'mtrl_name',             label: MTRL_NAME,           width: 150},
            {name: 'mtrl_prod_id_fk',  index: 'mtrl_prod_id_fk',       label: MTRL_PROD_ID_FK,     width: 150},
            {name: 'dest_shop',  index: 'dest_shop',       label: "备品备件仓",     width: 150},
            {name: 'apply_cate',       index: 'apply_cate',            label: APPLY_CATE,          width: 150},
            {name: 'apply_mtrl_qty',   index: 'apply_mtrl_qty',        label: APPLY_MTRL_QTY,      width: 150},
            {name: 'relate_mtrl_qty',  index: 'relate_mtrl_qty',  editable:true,  label: RELATE_MTRL_QTY,     width: 100},
            {name: 'repay_timestamp',  index: 'repay_timestamp',  editable:false, label: RELATE_TIMESTAMP,  width: 150},
            {name: 'evt_note',         index: 'evt_note',         editable:true,  label: EVT_NOTE,       width: 200},
        ];
        domObj.grids.$applyListGrd.jqGrid({
            url: "",
            datatype: "local",
            mtype: "POST",
            height: 400,
            width:600,
            autowidth: true,
            shrinkToFit:false,
            autoScroll: false,
            resizable: true,
            loadonce: true,
            viewrecords: true,
            rownumbers: true,
            rowNum: 20,
            multiselect : true,
            cellEdit:true,
            cellsubmit:"clientArray",
            colModel: toolListCM,
            pager: "#applyListPg",
            gridComplete:function(){
                var ids = domObj.grids.$applyListGrd.jqGrid('getDataIDs');
                for(var i=0;i < ids.length;i++){
                    var id = ids[i];
                    var data = domObj.grids.$applyListGrd.jqGrid('getRowData',id);
                    var dateBox ="<div name='dateBox' id='date"+id+"' class='input-group input-append'><input  id='dateBox"+id+"' data-format='yyyy-MM-dd' type='text' class='form-control' disabled><span class='input-group-addon add-on'><i data-date-icon='icon-calendar' class='glyphicon glyphicon-calendar'></i></span></div>";
                    domObj.grids.$applyListGrd.jqGrid('setRowData',ids[i],{repay_timestamp:dateBox});
                }
                toolFunc.iniDateBoxFunc();//初始化日期框
                for(var i=0;i < ids.length;i++){
                    var data = domObj.grids.$applyListGrd.jqGrid('getRowData',ids[i]);
                    if(data.apply_cate=='U:领用'){
                   /*   $("#date"+ ids[i]).datetimepicker('readonly');*/
                    }
                }
            }
        });
        var mtrlListCM = [
            {name: 'evt_seq_id',         index: 'evt_seq_id',            label: MTRL_PROD_ID_FK,  hidden:true,   width: 100},
            {name: 'apply_usr',          index: 'apply_usr',             label: APPLY_USR,           width: 150},
            {name: 'apply_timestamp',    index: 'apply_timestamp',       label: APPLY_TIMESTAMP,     width: 150},
            {name: 'mtrl_name',          index: 'mtrl_name',             label: MTRL_NAME,           width: 150},
            {name: 'mtrl_prod_id_fk',    index: 'mtrl_prod_id_fk',       label: MTRL_PROD_ID_FK,     width: 150},
            {name: 'dest_shop',    index: 'dest_shop',       label: "备品备件仓",     width: 150},
            {name: 'apply_cate',         index: 'apply_cate',            label: APPLY_CATE,          width: 150},
            {name: 'wait_repay_mtrl_qty',index: 'wait_repay_mtrl_qty',       label: WAIT_REPAY_MTRL_QTY ,width: 150},
            {name: 'act_repay_mtrl_qty', index: 'act_repay_mtrl_qty',    label: ACT_REPAY_MTRL_QTY, editable:true,  width: 150},
            {name: 'evt_note',           index: 'evt_note',              label: EVT_NOTE,           editable:true,   width: 150},
            {name: 'force_comp_flg',     index: 'force_comp_flg',        label: FORCE_COMP_FLG,   hidden:true, width: 150},
            {name: 'compButton',         index: 'compButton',            label: FORCE_COMP_FLG,   hidden:true, align: "center",   width: 100},
        ];
        domObj.grids.$lendListGrd.jqGrid({
            url: "",
            datatype: "local",
            mtype: "POST",
            height: 400,
            autowidth: true,
            shrinkToFit:false,
            autoScroll: false,
            resizable: true,
            loadonce: true,
            viewrecords: true,
            rownumbers: true,
            rowNum: 20,
            multiselect : true,
            cellEdit:true,
            cellsubmit:"clientArray",
            colModel: mtrlListCM,
            pager: "#lendListPg",
            gridComplete:function(){
                var ids = domObj.grids.$lendListGrd.jqGrid('getDataIDs');
                for(var i=0;i < ids.length;i++){
                    var id = ids[i];
                    var data = domObj.grids.$lendListGrd.jqGrid('getRowData',id);
                    var button ="<input id='button"+id+"' class='switch' name='status'    type='checkbox' />";
                    domObj.grids.$lendListGrd.jqGrid('setRowData',ids[i],{compButton:button});
                    if(data.force_comp_flg=='Y'){
                        $("#button"+ id).attr("checked", true);
                    }
                }
                toolFunc.iniSwitchFunc();//初始化switch框
            }
        });
    };
    var toolFunc = {
        iniToolTypeSel :function(){
            SelectDom.addSelectArr(domObj.$applyType, data, "data_ext","data_desc","",true);
        },
        iniToolSel :function(){
            var iary={
            		mtrl_cate : 'BACK'
            }
            var inObj = {
                trx_id : VAL.T_FBPBISMTR,
                action_flg : "Q",
                iary : [iary]
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                SelectDom.addSelectArr(domObj.$toolNameId, outObj.oary, "mtrl_prod_id","mtrl_prod_dsc","",true);
            }
        },
        iniSwitchFunc  :function(){
            $('[name="status"]').bootstrapSwitch({
                onText:"是",
                offText:"否",
                onColor:"success",
                offColor:"danger",
                size:"mini"
            })
        },
        iniDateBoxFunc  :function(){
            $('[name="dateBox"]').datetimepicker({
                language : 'zh-CN',
                autoclose : true,
                format: "yyyy-MM-dd",
                pickTime : false
            });
        },

        initBackDest : function(){
            var inObj = {
                trx_id : VAL.T_FBPBISDAT,
                action_flg : "Q",
                iary : [{
                    data_cate: 'DEST',
                    data_item  : 'C'
                }]
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                SelectDom.addSelectArr($("#backDest"), outObj.oary, "data_ext","data_desc","",true);
            }
        }
    };
    var btnFunc = {
        queryApplyFunc  :function(){
            var mtrlProdId  = $.trim(domObj.$toolNameId.val());
            var applyType    = $.trim(domObj.$applyType.val());
            var destShop = $("#backDest").find("option:selected").val();
            var iary={
            	mtrl_prod_id_fk : mtrlProdId,
                apply_stat : 'INPR',
                apply_cate : applyType,
                dest_shop : destShop
            }
            var inObj = {
                trx_id : VAL.T_MTPMTRLAPY,
                action_flg : "M",
                iary : [iary]
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                for(var i=0;i<outObj.oaryB.length;i++){
                    if(outObj.oaryB[i].apply_cate=='L'){
                        outObj.oaryB[i].apply_cate='L:借用'
                    }else {
                        outObj.oaryB[i].apply_cate='U:领用'
                    }
                }
                setGridInfo(outObj.oaryB, domObj.grids.$applyListGrd);
            }
        },
        queryLendFunc  :function(){
            var mtrlProdId  = $.trim(domObj.$toolNameId.val());
            var applyType    = $.trim(domObj.$applyType.val());
            var destShop = $("#backDest").find("option:selected").val();
            if(applyType!='L'){
            	domObj.grids.$lendListGrd.jqGrid("clearGridData");
                return false;
            }
            var iary={
            	mtrl_prod_id_fk : mtrlProdId,
                apply_stat : 'WAIT',
                apply_cate : applyType,
                dest_shop : destShop
            }
            var inObj = {
                trx_id : VAL.T_MTPMTRLAPY,
                action_flg : "M",
                iary : [iary]
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                for(var i=0;i<outObj.oaryB.length;i++){
                    if(outObj.oaryB[i].apply_cate=='L'){
                        outObj.oaryB[i].apply_cate='L:借用'
                    }else {
                        outObj.oaryB[i].apply_cate='U:领用'
                    }
                }
                setGridInfo(outObj.oaryB, domObj.grids.$lendListGrd);
            }
        },
        saveFunc  :function(){
            var idA = domObj.grids.$applyListGrd.jqGrid('getGridParam','selarrrow');
            var idL = domObj.grids.$lendListGrd.jqGrid('getGridParam','selarrrow');
            if(idA.length<1&&idL.length<1){
                showErrorDialog("", "至少选择一条数据进行保存");
                return false;
            }
            var iaryA =[],iaryB =[];
            if(idA.length>0){//借用领用登记
                for(var i=0;i<idA.length;i++) {
                    if ($('#applyListGrd :text[role="textbox"]').length > 0) {
                        var v = $('#applyListGrd :text[role="textbox"]').val();
                        $('#applyListGrd :text[role="textbox"]').parent().attr('title', v);
                        $('#applyListGrd :text[role="textbox"]').parent().html(v);
                    }
                    var rowData = domObj.grids.$applyListGrd.jqGrid("getRowData", idA[i]);
                    if(!rowData.relate_mtrl_qty){
                        showErrorDialog("", "第'"+ $('#' + idA[i])[0].rowIndex +"'行实际登记数量不能为空");
                        return false;


                    }
                    if(!ComRegex.isNumber(rowData.relate_mtrl_qty)){
                        showErrorDialog("", "第"+ $('#' + idA[i])[0].rowIndex + "行实际登记数值格式不正确！");
                        return false;
                    }
                    if(rowData.apply_cate=='L:借用'){
                        /*var repay_timestamp = $("#date"+ idA[i]).data("datetimepicker").getLocalDate().format('yyyy-MM-dd');*/
                        var repay_timestamp = $("#dateBox"+ idA[i]).val();
                        if(!repay_timestamp){
                            showErrorDialog("", "第'"+ $('#' + idA[i])[0].rowIndex +"'行指定归还时间不能为空");
                            return false;
                        }
                        var apply_time = rowData.apply_timestamp;
                        if((new Date(repay_timestamp.replace(/-/g,"\/"))) < (new Date(apply_time.replace(/-/g,"\/")))){
                            showErrorDialog("", "第'"+ $('#' + idA[i])[0].rowIndex +"'行指定归还时间不能在申请时间之前");
                            return false;
                        }
                    }
                    var iary={
                        evt_seq_id : rowData.evt_seq_id,
                        relate_mtrl_qty : rowData.relate_mtrl_qty,
                        repay_timestamp : repay_timestamp,
                        evt_note : rowData.evt_note,
                        evt_usr : VAL.EVT_USER
                    }
                    iaryA.push(iary);
                }
            }
            if(idL.length>0){//借用归还信息
                for(var i=0;i<idL.length;i++) {
                    if ($('#lendListGrd :text[role="textbox"]').length > 0) {
                        var v = $('#lendListGrd :text[role="textbox"]').val();
                        $('#lendListGrd :text[role="textbox"]').parent().attr('title', v);
                        $('#lendListGrd :text[role="textbox"]').parent().html(v);
                    }
                    var rowData = domObj.grids.$lendListGrd.jqGrid("getRowData", idL[i]);
                    if(!rowData.act_repay_mtrl_qty){
                        showErrorDialog("", "第'"+ $('#' + idL[i])[0].rowIndex +"'行归还数量不能为空");
                        return false;
                    }
                    if(!ComRegex.isNumber(rowData.act_repay_mtrl_qty)){
                        showErrorDialog("", "第"+ $('#' + idL[i])[0].rowIndex + "行归还数量数值格式不正确！");
                        return false;
                    }
                    var forceFlg = $("#button"+ idL[i]).bootstrapSwitch('state');
                    var force_comp_flg;
                    if(forceFlg){
                        force_comp_flg='Y';
                    }else{
                        force_comp_flg='N';
                    }
                    var iary={
                        evt_seq_id          : rowData.evt_seq_id,
                        act_repay_mtrl_qty  : rowData.act_repay_mtrl_qty,
                        evt_note            : rowData.evt_note,
                        force_comp_flg      : force_comp_flg
                    }
                    iaryB.push(iary);
                }
            }
            var inObj = {
                trx_id : VAL.T_MTPMTRLAPY,
                action_flg : "O",
                evt_usr : VAL.EVT_USER,
                iary  : iaryA,
                iaryB : iaryB,
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                showSuccessDialog("保存成功");
                btnFunc.queryApplyFunc();
                btnFunc.queryLendFunc();
            }


        },
    };

    /**
     * Ini contorl's data
     */
    var iniContorlData = function(){
        toolFunc.iniToolTypeSel();
        toolFunc.iniToolSel();
        toolFunc.initBackDest();
    };
    /**
     * Bind button click action
     */
    var iniButtonAction = function(){
        domObj.buttons.$query_btn.click(function(){
            btnFunc.queryApplyFunc();
            btnFunc.queryLendFunc();
        });
        domObj.buttons.$save_btn.click(function(){
            btnFunc.saveFunc();
        });
    };
    /**
     * Other action bind
     */
    var otherActionBind = function(){
        $("form").submit(function(){
            return false;
        });
    };
    /**
     * Ini view, data and action bind
     */
    var initializationFunc = function(){
        iniGridInfo();
        iniContorlData();
        iniButtonAction();
        otherActionBind();
    };

    initializationFunc();
    //表格自适应
    function resizeFnc(){
        var offsetBottom, divWidth,offsetBottom1, divWidth1;
        divWidth = $("#bottomDiv").width();
        offsetBottom =  $(window).height() - $("#bottomDiv").offset().top;
        $("#bottomDiv").height(offsetBottom * 0.95);
        $("#applyListGrd").setGridWidth(divWidth * 0.85);
        $("#applyListGrd").setGridHeight(offsetBottom * 0.99 - 51);
        //2
        divWidth1= $("#bottomDiv").width();
        offsetBottom1 =  $(window).height() - $("#bottomDiv").offset().top;
        $("#bottomDiv").height(offsetBottom1 * 0.95);
        $("#lendListGrd").setGridWidth(divWidth1 * 0.85);
        $("#lendListGrd").setGridHeight(offsetBottom1 * 0.99 - 51);

    };
    resizeFnc();
    $(window).resize(function() {
        resizeFnc();
    });
});
